import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '@/store'
import storage from '@/utils/storage' // sessionStorage

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // 跨域请求时发送cookies
  timeout: 5000 // 请求超时
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 设置请求头
    const token = storage.getItem('token')
    if (token) {
      config.headers['Authorization'] = storage.getItem('token')
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.log('err', error) // for debug
    console.log('err_response', error.response) // for debug
    //500 自定义的报错
    const response = error.response;
    if (response.status === 500 && response.data.status) {
      //获取响应体的实际状态码
      const status = response.data.status;
      // 401 token过期
      if (status === 401) {
        // 重新登录
        MessageBox.confirm('您已注销，可以取消以停留在此页面，或重新登录', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.href = '/login';
          })
        })
      } else if (status === 503) {
        Message({
          message: '服务不可用',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(error)
      }
      //剩下的全走通用异常处理
      Message({
        message: response.data.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (response.status == 503) {
      Message({
        message: '服务不可用',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      let {message} = error;
      if (message == "Network Error") {
        message = "后端接口连接异常";
      } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
      } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
      }
      Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
